<template>
  <div class="app-container">
    <el-row :gutter="15">
      <el-col :span="17" :xs="24" >
        <div class="container">
          <el-row>
            <el-col :span="24" :xs="24">
              <div class="title">传输设备<i class="el-icon-caret-right"></i>历史数据</div>
            </el-col>
          </el-row>
          <!-- 搜索 -->
          <el-row style="margin-left: 20px;">
            <el-col :span="24" :xs="24">
              <Search
                  :search-data="searchData"
                  :search-params="queryParams"
                  @change="searchParamsUpdate"
                  @selectChange="selectChange"
              >
              </Search>
            </el-col>
          </el-row>
          <!--    增加-->
          <el-row :gutter="10">
            <el-col :span="1">
              <right-toolbar :showSearch.sync="showSearch" :columns="columns"></right-toolbar>
            </el-col>
          </el-row>
          <!--      表格-->
          <el-table
              :data="tableData"
              height="66vh"
              style="width: 100%;background: #002127;"
              :cell-style="{backgroundColor: '#002127',color: '#ffffff',}"
              :header-cell-style="{ backgroundColor: '#00484D',textAlign: 'center',fontWeight: 'bold',color: '#ffffff',borderBottom: '1px solid #00484D' }">
            <el-table-column prop="deviceId" label="设备ID" align="center" v-if="columns[0].visible"></el-table-column>
            <el-table-column prop="deviceName" label="设备名称" align="center" v-if="columns[1].visible"></el-table-column>
            <el-table-column prop="channelId" label="通道ID" align="center" v-if="columns[2].visible"></el-table-column>
            <el-table-column prop="channel" label="通道名称" align="center" v-if="columns[3].visible"></el-table-column>
            <el-table-column label="值" align="center" v-if="columns[4].visible">
              <template slot-scope="scope" >
                <div>{{scope.row.value}}{{scope.row.unit}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="time" label="上报时间" align="center" v-if="columns[5].visible" show-overflow-tooltip sortable></el-table-column>
          </el-table>
          <!--    分页-->
          <el-row>
            <el-col :span="24" :xs="24">
              <pagination
                  :total="total"
                  :page.sync="queryParams.page"
                  :limit.sync="queryParams.limit"
              />
            </el-col>
          </el-row>
        </div>
      </el-col>
<!--       右侧-->
      <el-col :span="7" :xs="24" >
        <el-row style="margin-bottom: 20px;">
          <el-col :span="24" :xs="24">
            <div class="container" style="height: 430px;">
              <div class="title" style="margin-top: 0px;padding-top: 10px;">曲线分析</div>
              <div id="main" style="width: 100%;height:340px;"></div>
            </div>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 20px;">
          <el-col :span="24" :xs="24">
            <div class="container" style="height: 400px;">
              <div class="title" style="margin-top: 0px;padding-top: 10px;">极值统计</div>
              <el-table
                  :data="tableDatas"
                  style="width: 100%;background: #002127;"
                  :cell-style="{backgroundColor: '#002127',color: '#ffffff',}"
                  :header-cell-style="{ backgroundColor: '#00484D',fontWeight: 'bold',color: '#ffffff',borderBottom: '1px solid #00484D' }">
                <el-table-column prop="time" label="时间"></el-table-column>
                <el-table-column prop="max" label="最大值"></el-table-column>
                <el-table-column prop="min" label="最小值"></el-table-column>
                <el-table-column prop="average" label="平均值"></el-table-column>
                <el-table-column prop="warn" label="告警次数"></el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </el-col>
    </el-row>


  </div>
</template>

<script>
import {getHistoryByPage, getRuleAllList, getDtuAllList, getHistoryCurve, getHistoryPeak} from '@/api/automation'
import Search from '@/components/PageSearch'
import Pagination from "@/components/Pagination";
import RightToolbar from '@/components/RightToolbar'
export default {
  name: "history",
  components: { Search, Pagination, RightToolbar },
  data() {
    return {
      // 搜索
      searchData: [
        {
          type: 'select',
          label: '设备',
          prop: 'deviceId',
          options: [],
          placeholder: '请选择设备筛选'
        },
        {
          type: 'select',
          label: '通道',
          prop: 'channelId',
          options: [],
          placeholder: '请选择通道筛选'
        },
        {
          type: 'datetime',
          label: '开始时间',
          prop: 'startTime',
          placeholder: '请选择开始时间',
          pickerOptions: {
            disabledDate: (t) => {
              return this.queryParams.endTime ? t.getTime() > new Date(this.queryParams.endTime).getTime() - 86400000 : false
            }
          }
        },
        {
          type: 'datetime',
          label: '结束时间',
          prop: 'endTime',
          placeholder: '请选择结束时间',
          pickerOptions: {
            disabledDate: (t) => {
              return this.queryParams.startTime ? t.getTime() > new Date(this.queryParams.startTime).getTime() + 86400000*30 : false
              // this.queryParams.startTime ? t.getTime() < new Date(this.queryParams.startTime).getTime() : false
            }
            // disabledDate: (time) => {
            //   if (this.queryParams.startTime) {
            //     return (
            //         // time.getTime() <= new Date(this.queryParams.startTime).getTime()
            //         time.getTime() > new Date(this.queryParams.startTime).getTime() + 86400000*30
            //     );
            //   }
            // }
          }
        }
      ],
      // 分页总条数
      total: 0,
      // 查询参数
      queryParams: {
        page: 1,
        limit: 20,
        deviceId: '',
        channelId: '',
        startTime: '',
        endTime: '',
        time: ''
      },
      // 表格
      tableData: [],
      // 显示搜索条件
      showSearch: true,
      // 列信息
      columns: [
        { key: 0, label: `设备ID`, visible: true },
        { key: 1, label: `设备名称`, visible: true },
        { key: 2, label: `通道ID`, visible: false },
        { key: 3, label: `通道名称`, visible: true },
        { key: 4, label: `值`, visible: true },
        { key: 5, label: `上报时间`, visible: true }
      ],
      dtuOption: [],
      channelOption: [],
      tableDatas: [], //极值表
      charData:{
        up: [],
        down:[],
        value:[],
        time:[],
        names:'',
        queryData : null
      },
      deviceId: '',
      channelId: ''
    }
  },
  props: {},
  watch: {
    dtuOption: {
      handler(val) {
        this.searchData[0].options = this.dtuOption
      },
      immediate: true
    },
    channelOption: {
      handler(val) {
        this.searchData[1].options = this.channelOption
      },
      immediate: true
    },
  },
  created() {
    this.getDtuOption()
    // this.getList()
    // this.maps()
    let yesterday = new Date(new Date().setDate(new Date().getDate() - 1))
    this.queryParams.startTime = this.$moment(yesterday).format("YYYY-MM-DD HH:mm:ss")
    this.queryParams.endTime = this.$moment(new Date()).format("YYYY-MM-DD HH:mm:ss")
  },
  mounted() {
    this.chartA()
  },
  methods: {
    // maps() {
    //   var data = []
    //   var date = new Date().getTime()
    //   console.log('开始时间'+new Date())
    //   var i = 0 ;
    //   for(i;i<200000;i++) {
    //     date+= 5000
    //     data.push(new Date(date))
    //   }
    //   console.log('结束时间'+new Date())
    //   console.log(data)
    // },
    //设备下拉
    getDtuOption() {
      this.deviceId = this.$route.query.deviceId
      this.channelId = this.$route.query.channelId
      getDtuAllList().then(res => {
        const data = res.data
        this.dtuOption = data.map(item => {
          return {
            value: item.id,
            label: item.name
          }
        })
        if(this.deviceId && this.channelId) {
          // this.selectChange()
          this.queryParams.deviceId = this.deviceId;
          this.getChannelOption()
          this.queryParams.channelId = this.channelId
        }
      }).catch(err => {
        console.log(err)
      })
    },
    //通道下拉
    getChannelOption() {
      getRuleAllList(this.queryParams.deviceId).then(res => {
        const data = res.data
        this.channelOption = data.map(item => {
          return {
            value: item.id,
            label: item.name
          }
        });
        this.channelOption.map(item => {
          if( item.value == this.channelId) {
            item.value = this.channelId
            this.getCount()
          }
        })
      }).catch(err => {
        console.log(err)
      })
    },
    selectChange(val, item) {
      console.log('selectChange', val, item)
      if(item == 'deviceId' && this.queryParams.deviceId !=''){
        this.queryParams.channelId = ''
        this.getChannelOption()
      }
      if(item == 'channelId'){
        this.getCount()
      }
      // this.getChannelOption()
      // if(this.queryParams.deviceId !=''&& this.queryParams.channelId !='') {
      //   this.getCount()
      // }
    },
    getList() {
      getHistoryByPage(this.queryParams).then((res) => {
        console.log(res)
        this.total = res.dataCounts
        this.tableData = res.data || []
      }).catch((err) => {
        console.log(err)
        // this.$message.error(err.errorMsg)
      })
    },
    // 新的搜索内容
    searchParamsUpdate() {
      if(this.queryParams.deviceId !=''){
        this.getList()
      }
      if(this.queryParams.deviceId !='' && this.queryParams.channelId !=''&&this.queryParams.startTime !='' && this.queryParams.endTime !='') {
        this.chartB()
      }
    },
    //  极值统计
    getCount() {
      const data = {
        limit: 20,
        page: 1,
        channelId: this.queryParams.channelId,
        deviceId: this.queryParams.deviceId,
        time: '',
        startTime: this.queryParams.startTime,
        endTime: this.queryParams.endTime
      }
      getHistoryPeak(data)
          .then((res) => {
            this.tableDatas = res.data || []
          })
          .catch((err) => {
            console.log(err)
            // this.$message.error(err.errorMsg)
          })
    },
    //  曲线分析
    chartA() {
      const myChart = this.$echarts.init(document.getElementById('main'))  // 先获得这个dom元素并初始化
      // 指定图表的配置项和数据
      myChart.setOption({
        backgroundColor:'#002127',
        // 指示线
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: "#006675"
            }
          }
        },
        // 折线颜色
        color: ['#006675'],
        // 图表距离容器距离
        grid: {
          left: '2%',
          right: '2%',
          top: '5%',
          bottom: '5%',
          containLabel: true
        },
        xAxis: [{
          show: true,
          type: 'category',
          // 隐藏横向网格线
          splitLine: {
            show: false
          },
          data: ['2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010'],
          // x轴字体设置
          axisLabel: {
            rotate: 0, //倾斜角度
            color: '#ffffff',
          },
          // 横坐标刻度线
          axisTick: {
            show: false
          },
          // 坐标轴
          axisLine: {
            lineStyle: {
              color: '#999999',
            }
          },
          // y轴与坐标轴线对齐
          boundaryGap: true,
        }],
        yAxis: [{
          // name: '(mA)',
          type: 'value',
          // min: 0,
          // max: 250,
          // y轴字体设置
          axisLabel: {
            color: '#ffffff',
          },
          // y轴线条
          axisLine: {
            show: false
          },
          // 刻度线
          axisTick: {
            show: true
          },
          // 网格线
          splitLine: {
            show: true,
            lineStyle: {
              color: '#999999',
              type:'dashed',
            }
          }
        }],
        series: [
          {
            name: '设备数',
            type: 'line',
            smooth: true,
            symbolSize: 4,
            data: ['40', '80', '50', '170', '70', '100', '80', '180', '40', '10'],
          },
          {
            name:'上限值',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 4,
            itemStyle: {
              color: '#ffc500',
              borderColor: "#fff",
              borderWidth: 1,
            },
            data: [100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
          },
          {
            name:'下限值',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 4,
            itemStyle: {
              color: '#ff5b29',
              borderColor: "#fff",
              borderWidth: 1,
            },
            data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
          }
        ]
      });
    },
    chartB() {
      this.charData = {
        up: [], down:[], value:[], time:[], names:''
      }
      this.charData.queryData = new Date(this.queryParams.startTime).getTime();
      // var startTime = new Date(this.queryParams.startTime).getTime()
      // var endTime = new Date(this.queryParams.endTime).getTime()
      // for ( var i = 0 ; i < 1 ; i++ ) {
      // for ( startTime ; startTime < endTime ; ) {
      this.chartC()
      // }
    },
    chartC() {
      const data = {
        channelId: this.queryParams.channelId,
        deviceId: this.queryParams.deviceId,
        startTime: this.$moment(this.charData.queryData).format("YYYY-MM-DD HH:mm:ss"),
        endTime: this.$moment(this.charData.queryData + 1000*60*60*24).format("YYYY-MM-DD HH:mm:ss")
      }
      this.charData.queryData = this.charData.queryData + 1000*60*60*24
      getHistoryCurve(data)
          .then((res) => {
            const length = res.data.time.length
            for ( let i = 0 ; i < length ; i++ ) {
              this.charData.up.push(res.data.up[0]);
              this.charData.down.push(res.data.down[0]);
            }
            // this.charData.up = this.charData.up.concat(res.data.up)
            // this.charData.down = this.charData.down.concat(res.data.down)
            this.charData.value = this.charData.value.concat(res.data.value)
            this.charData.time = this.charData.time.concat(res.data.time)
            this.charData.names=res.data.channelName
            this.char();
            if ( this.charData.queryData < new Date(this.queryParams.endTime).getTime() ) {
              this.chartC()
            }
          })
          .catch((err) => {
            console.log(err)
            // this.$message.error(err.errorMsg)
          })
    },
    char() {
      const myChart = this.$echarts.init(document.getElementById('main'))
      const up = this.charData.up
      const down = this.charData.down
      const value = this.charData.value
      const time = this.charData.time
      console.log()
      const names = this.charData.names
      myChart.setOption({
        backgroundColor:'#002127',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: "#006675"
            }
          }
        },
        color: ['#006675'],
        grid: {
          left: '2%',
          right: '2%',
          top: '13%',
          bottom: '8%',
          containLabel: true
        },
        xAxis: [{
          show: true,
          type: 'category',
          splitLine: {
            show: false
          },
          data: time,
          axisLabel: {
            rotate: 0,
            color: '#ffffff',
          },
          axisTick: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: '#999999',
            }
          },
          boundaryGap: true,
        }],
        yAxis: [{
          type: 'value',
          axisLabel: {
            color: '#ffffff',
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#999999',
            }
          }
        }],
        series: [
          {
            name: names,
            type: 'line',
            smooth: true,
            symbolSize: 4,
            data: value,
          },
          {
            name:'上限值',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 4,
            itemStyle: {
              color: '#ffc500',
              borderColor: "#fff",
              borderWidth: 1,
            },
            data: up
          },
          {
            name:'下限值',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 4,
            itemStyle: {
              color: '#ff5b29',
              borderColor: "#fff",
              borderWidth: 1,
            },
            data: down
          }
        ]
      });
      myChart.resize();
    }
  }
}
</script>

<style lang='less' scoped>
.app-container {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  background: #0C323A;
  .container {
    width: 100%;
    height: 100%;
    background: #002127;
    border-radius: 10px;
    .title {
      height: 42px;
      line-height: 42px;
      border-bottom: 1px solid #999999;
      color: #ffffff;
      font-size: 14px;
      margin-bottom: 15px;
      padding-left: 20px;
      margin-top: 10px;
    }
    // 显隐列
    .el-col-1 {
      float: right;
    }
  }
}
// 表格设置鼠标经过时背景颜色
::v-deep.el-table tbody tr:hover>td{
  background-color: #02565c !important;
}
//表格改变每行底边框颜色
::v-deep.el-table  td, .el-table th.is-leaf  {
  border-bottom:  1px solid rgba(0,231,231,0.302)!important;
}
/*table边框颜色*/
.el-table--border:after,
.el-table--group:after,
.el-table:before {
  background-color: #002127;
}
</style>
